import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Checkbox, Notification, Space } from 'antd';
import { goBack } from '@/utils/util';
import ChooseUser from '@/components/ChooseUser';
import UploadList from '@/components/UploadList';
import FileLists from '@/components/FileLists';

import E from 'wangeditor';
import API from '@/api/xjindex.js';
import './index.less';

let editor = null;

const noticeComponent = ({ id, readOnly }) => {
  // 文件上传格式
  const uploadOptions = {
    fileTypes: [
      'application/doc',
      'application/pdf',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'image/jpg',
      'image/jpeg',
      'image/png',
    ],
    maxSize: 50,
    maxNum: 3,
    accept: [
      '.doc,.docx.,.pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,.jpg,.jpeg,.png',
    ],
    acceptMessage: 'jpg/word/pdf',
  };

  const [form] = Form.useForm();
  const [fileList, setFileList] = useState([]);
  const remindWayOptions = [
    { label: '系统消息', value: '1' },
    { label: '短信消息', value: '2' },
  ];

  // 获取详情
  const initDetail = () => {
    API.showAffiche({
      id,
    }).then((res) => {
      if (res) {
        const resObj = {
          acceptId: res.t.acceptId,
          acceptName: res.t.acceptName,
          noticeName: res.t.noticeName,
          details: res.t.details,
          afficheFileList: res.t.afficheFileList,
          remindWay: res.t.remindWay.toString(),
        };
        form.setFieldsValue(resObj);
        editor.txt.html(res.t.details);
        if (readOnly) {
          editor.$textElem.attr('contenteditable', false);
        }
        setFileList(res.t.afficheFileList);
      }
    });
  };

  // 提交
  const submitFn = (flge) => {
    const value = form.getFieldsValue(true);
    if (value.remindWay.length > 1) {
      value.remindWay = '3';
    } else {
      value.remindWay = value.remindWay[0];
    }
    value.flge = flge; // 1:保存，2:发布
    if (id) {
      value.id = id;
      value.type = '2'; // 修改
    } else {
      value.type = '1'; // 新增
    }
    form.validateFields().then(() => {
      API.addAffiche(value).then((res) => {
        if (res) {
          const title = !id ? '新增' : '更新';
          Notification.success({
            message: title + '成功',
          });
          goBack();
        }
      });
    });
  };

  useEffect(() => {
    editor = new E('#detailsDiv');
    editor.create();
    editor.config.onchange = () => {
      form.setFieldsValue({
        details: editor.txt.html(),
      });
    };
    return () => {
      editor.destroy();
    };
  }, []);

  useEffect(() => {
    if (id) {
      initDetail();
    } else {
      form.setFieldsValue({
        noticeName: '',
        details: '',
        remindWay: '1',
      });
    }
  }, [id]);

  const getUsers = (values) => {
    form.setFieldsValue({
      acceptId: values.userIds.join(','),
      acceptName: values.userNames.join(','),
    });
  };

  return (
    <>
      <div className="main-x">
        <Form className="componentForm max-x" form={form} onFinish={submitFn}>
          <div className="search-x bgf">
            <Form.Item
              label="公告标题"
              name="noticeName"
              style={{ width: '100%' }}
              rules={[{ required: true, message: '公告标题不能为空' }]}
            >
              <Input readOnly={readOnly}></Input>
            </Form.Item>
            <Form.Item
              label="接收人员"
              name="acceptId"
              style={{ width: '100%' }}
              rules={[
                {
                  required: true,
                  message: '请选择接收人员',
                },
              ]}
            >
              <ChooseUser
                userIds={form.getFieldValue('acceptId')}
                userNames={form.getFieldValue('acceptName')}
                readOnly={readOnly}
                onUserChange={getUsers}
              />
            </Form.Item>
            <Form.Item name="acceptName" style={{ display: 'none' }}>
              <Input></Input>
            </Form.Item>
            <Form.Item
              label="公告详情"
              name="details"
              style={{ width: '100%' }}
              rules={[{ required: true, message: '公共详情不能为空' }]}
            >
              <div id="detailsDiv"></div>
            </Form.Item>
            {readOnly ? (
              <>
                <Form.Item
                  label="文件上传"
                  className="block"
                  style={{ width: '100%' }}
                >
                  <FileLists
                    fileList={fileList}
                    downloadUrl="/affiche/download"
                  ></FileLists>
                </Form.Item>
              </>
            ) : (
              <>
                <Form.Item
                  label="文件上传"
                  extra="支持jpg/word/pdf格式,单个大小在50M以内"
                  name="afficheFileList"
                  className="block"
                  rules={[{ required: true, message: '请上传文件' }]}
                >
                  <UploadList
                    uploadUrl="/affiche/fileUpload"
                    downloadUrl="/affiche/download"
                    options={uploadOptions}
                    defaultFiles={fileList}
                  ></UploadList>
                </Form.Item>
              </>
            )}
            <Form.Item
              label="提醒方式"
              name="remindWay"
              style={{ width: '100%' }}
              rules={[{ required: true, message: '请选择提醒方式' }]}
            >
              <Checkbox.Group
                options={remindWayOptions}
                initialvalues={['1']}
                disabled={readOnly}
              />
            </Form.Item>
          </div>
          <div className="footer-x">
            {readOnly ? (
              <Button
                type="primary"
                htmlType="reset"
                className="cancel-btn"
                onClick={goBack}
              >
                返回
              </Button>
            ) : (
              <Space size={18}>
                <Button type="primary" onClick={submitFn.bind(null, '1')}>
                  保存
                </Button>
                <Button type="primary" onClick={submitFn.bind(null, '2')}>
                  提交
                </Button>
                <Button
                  type="primary"
                  htmlType="reset"
                  className="cancel-btn"
                  onClick={goBack}
                >
                  返回
                </Button>
              </Space>
            )}
          </div>
        </Form>
      </div>
    </>
  );
};

export default noticeComponent;
